﻿Type.registerNamespace("BM");

BM.Stylesheet = {
    getRules: function(ss) {
        if (ss.cssRules)
            return ss.cssRules;
        else if (ss.rules)
            return ss.rules;
    },

    findIndex: function(ss, selector) {
        var rules = BM.Stylesheet.getRules(ss);
        if (!rules) return;
        for (var i = 0; i < rules.length; i++) {
            if (rules[i].selectorText && rules[i].selectorText.equalsIgnoreCase(selector)) {
                return i;
            }
        }
    },

    findStartsWithIndex: function(ss, selector) {
        selector = selector.toLowerCase();
        var rules = BM.Stylesheet.getRules(ss);
        if (!rules) return;
        for (var i = 0; i < rules.length; i++) {
            if (rules[i].selectorText && rules[i].selectorText.toLowerCase().startsWith(selector)) {
                return i;
            }
        }
    },

    find: function(ss, selector, startsWith) {
        var index;
        if (startsWith) {
            index = BM.Stylesheet.findStartsWithIndex(ss, selector);
        } else {
            index = BM.Stylesheet.findIndex(ss, selector);
        }
        if (index == null) return;
        return BM.Stylesheet.getRules(ss)[index];
    },

    add: function(ss, selector, declaration) {
        var index = BM.Stylesheet.findIndex(ss, selector);
        if (index != null) {
            return BM.Stylesheet.appendDeclaration(BM.Stylesheet.getRules(ss)[index], declaration);
        }
        if (typeof ss.addRule != 'undefined') {
            ss.addRule(selector, declaration);
        } else if (typeof ss.insertRule != 'undefined') {
            ss.insertRule(selector + "{" + declaration + "}", BM.Stylesheet.getRules(ss).length);
        }
    },

    remove: function(ss, selector) {
        var index = BM.Stylesheet.findIndex(ss, selector);
        if (index == null) return;
        if (typeof ss.removeRule != 'undefined') {
            ss.removeRule(index);
        } else if (typeof ss.deleteRule != 'undefined') {
            ss.deleteRule(index);
        }
    },

    appendDeclaration: function(rule, declaration) {
        rule.style.cssText += ";" + declaration;
    },

    set: function(rule, properties, values) {
        try {
            rule.style.cssText = "";
            for (var i = 0; i < properties.length; i++) {
                rule.style.cssText += properties[i] + ":" + values[i] + "; ";
            }
        } catch (e) { }
        for (var i = 0; i < properties.length; i++) {
            rule.style[properties[i]] = values[i];
        }
    }
}